import websocket
import time
import json
from decimal import Decimal as D

import threading

from gate_api import ApiClient, Configuration, Order, SpotApi
class gate_exchange:


    def __init__(self,exchange_key,exchange_secret):
        self.ws = websocket.WebSocketApp("wss://api.gateio.ws/ws/v4/",
                                    on_message=self.on_message,
                                    on_error=self.on_error,
                                    on_close=self.on_close,
                                         on_open=self.on_open)
        #要做异步处理

        thread_task = threading.Thread(target=self.ws.run_forever,name="run_forever")
        thread_task.start()
        config = Configuration(key=exchange_key,
                               secret=exchange_secret)

        self.gate_spot_api = SpotApi(ApiClient(config))

        self.depth = None
        time.sleep(4)

    def create_order(self,order_amount,last_price,side,currency_pair,order_type):
        order = Order(amount=str(order_amount), price=last_price, side=side, currency_pair=currency_pair,type=order_type)
        return self.gate_spot_api.create_order(order)

    def get_order(self,order_id,currency_pair):
        return self.gate_spot_api.get_order(order_id=order_id,currency_pair=currency_pair)

    def cancel_order(self,order_id,currency_pair):
        return self.gate_spot_api.cancel_order(order_id=order_id,currency_pair=currency_pair)

    def get_account(self,symbol):
        accounts = self.gate_spot_api.list_spot_accounts(currency=symbol)
        if len(accounts) == 1:
            return D(accounts[0].available)
        return D('0.0')

    def get_all_accounts(self):
        return self.gate_spot_api.list_spot_accounts()


    def get_depth(self,symbol):
        return self.depth

    def on_message(self,_, message):
        message_obj = json.loads(message)
        if message_obj['event'] == 'update':
            self.depth = json.loads(message)

        elif message_obj['event'] == 'subscribe':
            pass
        else:
            print("Received message:", message)

    def on_error(self,_,error):
        print("Error:", error)

    def on_close(self,_):
        print("### closed ###")

    def on_open(self,_):
        print("on_open")



    def subscribe_depth_message(self,symbol):

        self.ws.send(json.dumps({
            "time": int(time.time()),
            "channel": "spot.order_book",
            "event": "subscribe",  # "unsubscribe" for unsubscription
            "payload": [symbol, "5", "100ms"]
        }))




if __name__ == "__main__":
    gate_key = "3e8bf1c102bedfdea327212db1b466be"
    gate_secret = "d8d6024fa11a053f71d7dd20c1ce0713335d0b4e88e80ba11a844c00684e1d84"
    e =gate_exchange(gate_key,gate_secret)
    # e.subscribe_depth_message("PEPE_USDT")
    # e.get_account("USDT")
    accounts = e.gate_spot_api.list_spot_accounts()
    print("runing")

    # accounts = spot_api.list_spot_accounts(currency="USDT")
    # print(accounts)